const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const compression = require('compression');
const rateLimit = require('express-rate-limit');
const { createServer } = require('http');
const { Server } = require('socket.io');
require('dotenv').config();

const logger = require('./utils/logger');
const SocketService = require('./utils/socketService');
const NotificationService = require('./utils/notificationService');
const { globalErrorHandler, AppError } = require('./middleware/errorHandler');
const notFound = require('./middleware/notFound');

// 路由导入
const authRoutes = require('./routes/authRoutes');
const userRoutes = require('./routes/userRoutes');
const petRoutes = require('./routes/petRoutes');
const orderRoutes = require('./routes/orderRoutes');
// const caregiverRoutes = require('./routes/caregiverRoutes'); // 暂时禁用，等待重构完成
const serviceRoutes = require('./routes/serviceRoutes');
const locationRoutes = require('./routes/locationRoutes');
const paymentRoutes = require('./routes/paymentRoutes');

const app = express();
const server = createServer(app);
const io = new Server(server, {
  cors: {
    origin: process.env.FRONTEND_URL || 'http://localhost:3001',
    methods: ['GET', 'POST']
  }
});

// 中间件配置
app.use(helmet()); // 安全头
app.use(compression()); // 压缩响应
app.use(cors({
  origin: process.env.FRONTEND_URL || 'http://localhost:3001',
  credentials: true
}));

// 速率限制
const limiter = rateLimit({
  windowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS) || 15 * 60 * 1000, // 15分钟
  max: parseInt(process.env.RATE_LIMIT_MAX_REQUESTS) || 100, // 限制每个IP 100个请求
  message: {
    error: '请求过于频繁，请稍后再试'
  }
});
app.use('/api/', limiter);

app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 初始化Socket服务
const socketService = new SocketService(io);

// 初始化通知服务
const notificationService = new NotificationService(socketService);

// 将服务实例添加到 app 中，供路由使用
app.set('io', io);
app.set('socketService', socketService);
app.set('notificationService', notificationService);

// 定期清理非活跃连接
setInterval(() => {
  socketService.cleanupInactiveConnections();
}, 10 * 60 * 1000); // 每10分钟清理一次

// API 路由
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/pets', petRoutes);
app.use('/api/orders', orderRoutes);
// app.use('/api/caregivers', caregiverRoutes); // 暂时禁用，等待重构完成
app.use('/api/services', serviceRoutes);
app.use('/api/location', locationRoutes);
app.use('/api/payment', paymentRoutes);

// 健康检查端点
app.get('/health', (req, res) => {
  res.status(200).json({
    status: 'OK',
    timestamp: new Date().toISOString(),
    uptime: process.uptime(),
    environment: process.env.NODE_ENV || 'development'
  });
});

// 根路径
app.get('/', (req, res) => {
  res.json({
    message: '欢迎使用宠物上门喂养服务平台 API',
    version: '1.0.0',
    documentation: '/api/docs'
  });
});

// 错误处理中间件
app.use(notFound);
app.use(globalErrorHandler);

module.exports = { app, server };